
document.addEventListener('DOMContentLoaded', () => {
    const captchaImage = document.getElementById('captchaImage');
    const captchaInput = document.getElementById('captcha');
    
    // 生成随机验证码文本
    function generateCaptchaText() {
        const chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        let captcha = '';
        for (let i = 0; i < 4; i++) {
            captcha += chars.charAt(Math.floor(Math.random() * chars.length));
        }
        return captcha;
    }
    
    // 绘制验证码图片
    function drawCaptcha() {
        const captchaText = generateCaptchaText();
        // 存储验证码文本用于验证
        sessionStorage.setItem('captchaCode', captchaText);
        
        const canvas = document.createElement('canvas');
        canvas.width = 120;
        canvas.height = 48;
        const ctx = canvas.getContext('2d');
        
        // 绘制背景
        ctx.fillStyle = '#f9fbfd';
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        
        // 绘制干扰线
        for (let i = 0; i < 5; i++) {
            ctx.strokeStyle = `rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 200})`;
            ctx.beginPath();
            ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
            ctx.stroke();
        }
        
        // 绘制干扰点
        for (let i = 0; i < 30; i++) {
            ctx.fillStyle = `rgb(${Math.random() * 200}, ${Math.random() * 200}, ${Math.random() * 200})`;
            ctx.beginPath();
            ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI);
            ctx.fill();
        }
        
        // 绘制验证码文本
        ctx.font = 'bold 24px Arial';
        for (let i = 0; i < captchaText.length; i++) {
            const char = captchaText.charAt(i);
            ctx.fillStyle = `rgb(${Math.random() * 100}, ${Math.random() * 100}, ${Math.random() * 100})`;
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            // 随机旋转每个字符
            const x = 25 + i * 20;
            const y = canvas.height / 2;
            const angle = (Math.random() - 0.5) * 0.5; // 随机角度
            
            ctx.save();
            ctx.translate(x, y);
            ctx.rotate(angle);
            ctx.fillText(char, 0, 0);
            ctx.restore();
        }
        
        // 将canvas转换为图片
        captchaImage.src = canvas.toDataURL('image/png');
    }
    
    // 初始生成验证码
    drawCaptcha();
    
    // 点击验证码图片刷新
    captchaImage.addEventListener('click', drawCaptcha);
    
    // 暴露验证码验证函数供登录逻辑调用
    window.validateCaptcha = function() {
        const userInput = captchaInput.value.trim().toUpperCase();
        const captchaCode = sessionStorage.getItem('captchaCode')?.toUpperCase() || '';
        return userInput === captchaCode;
    };
});